/**
 * 剪贴板工具
 * 用于复制和粘贴功能
 */

import { ref } from 'vue'
import { showToast } from 'vant'

/**
 * 剪贴板组合式函数
 * @returns {object} 剪贴板相关方法和状态
 */
export function useClipboard() {
  const isSupported = ref(false)
  const text = ref('')

  // 检查浏览器是否支持剪贴板API
  const checkSupport = () => {
    isSupported.value = !!(navigator.clipboard && navigator.clipboard.writeText)
    return isSupported.value
  }

  /**
   * 复制文本到剪贴板
   * @param {string} textToCopy - 要复制的文本
   * @param {boolean} showMessage - 是否显示提示消息
   * @returns {Promise<boolean>} 复制是否成功
   */
  const copy = async (textToCopy, showMessage = true) => {
    try {
      if (checkSupport()) {
        // 使用现代剪贴板API
        await navigator.clipboard.writeText(textToCopy)
      } else {
        // 降级方案：使用传统方法
        await copyFallback(textToCopy)
      }
      
      text.value = textToCopy
      
      if (showMessage) {
        showToast({
          message: '复制成功',
          type: 'success',
          duration: 1500
        })
      }
      
      return true
    } catch (error) {
      console.error('复制失败:', error)
      
      if (showMessage) {
        showToast({
          message: '复制失败',
          type: 'fail',
          duration: 1500
        })
      }
      
      return false
    }
  }

  /**
   * 从剪贴板读取文本
   * @returns {Promise<string>} 剪贴板中的文本
   */
  const read = async () => {
    try {
      if (checkSupport()) {
        const clipboardText = await navigator.clipboard.readText()
        text.value = clipboardText
        return clipboardText
      } else {
        throw new Error('浏览器不支持读取剪贴板')
      }
    } catch (error) {
      console.error('读取剪贴板失败:', error)
      return ''
    }
  }

  /**
   * 传统复制方法（降级方案）
   * @param {string} textToCopy - 要复制的文本
   * @returns {Promise<void>}
   */
  const copyFallback = (textToCopy) => {
    return new Promise((resolve, reject) => {
      const textArea = document.createElement('textarea')
      textArea.value = textToCopy
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      
      try {
        const successful = document.execCommand('copy')
        document.body.removeChild(textArea)
        
        if (successful) {
          resolve()
        } else {
          reject(new Error('复制命令执行失败'))
        }
      } catch (error) {
        document.body.removeChild(textArea)
        reject(error)
      }
    })
  }

  /**
   * 清空剪贴板
   * @returns {Promise<boolean>} 清空是否成功
   */
  const clear = async () => {
    return await copy('', false)
  }

  // 初始化检查支持性
  checkSupport()

  return {
    isSupported,
    text,
    copy,
    read,
    clear
  }
}

/**
 * 快速复制文本
 * @param {string} text - 要复制的文本
 * @param {boolean} showMessage - 是否显示提示消息
 * @returns {Promise<boolean>} 复制是否成功
 */
export const copyText = async (text, showMessage = true) => {
  const { copy } = useClipboard()
  return await copy(text, showMessage)
}

/**
 * 复制对象为JSON字符串
 * @param {object} obj - 要复制的对象
 * @param {boolean} showMessage - 是否显示提示消息
 * @returns {Promise<boolean>} 复制是否成功
 */
export const copyObject = async (obj, showMessage = true) => {
  try {
    const jsonString = JSON.stringify(obj, null, 2)
    return await copyText(jsonString, showMessage)
  } catch (error) {
    console.error('对象序列化失败:', error)
    
    if (showMessage) {
      showToast({
        message: '复制失败：对象格式错误',
        type: 'fail',
        duration: 1500
      })
    }
    
    return false
  }
}

/**
 * 复制URL
 * @param {string} url - 要复制的URL
 * @param {boolean} showMessage - 是否显示提示消息
 * @returns {Promise<boolean>} 复制是否成功
 */
export const copyUrl = async (url, showMessage = true) => {
  // 如果是相对路径，转换为绝对路径
  let fullUrl = url
  if (url.startsWith('/')) {
    fullUrl = window.location.origin + url
  } else if (!url.startsWith('http')) {
    fullUrl = window.location.origin + '/' + url
  }
  
  return await copyText(fullUrl, showMessage)
}

/**
 * 复制当前页面URL
 * @param {boolean} showMessage - 是否显示提示消息
 * @returns {Promise<boolean>} 复制是否成功
 */
export const copyCurrentUrl = async (showMessage = true) => {
  return await copyText(window.location.href, showMessage)
}

/**
 * 复制表格数据为CSV格式
 * @param {Array} data - 表格数据
 * @param {Array} headers - 表头
 * @param {boolean} showMessage - 是否显示提示消息
 * @returns {Promise<boolean>} 复制是否成功
 */
export const copyTableAsCSV = async (data, headers = [], showMessage = true) => {
  try {
    let csvContent = ''
    
    // 添加表头
    if (headers.length > 0) {
      csvContent += headers.join(',') + '\n'
    }
    
    // 添加数据行
    data.forEach(row => {
      if (Array.isArray(row)) {
        csvContent += row.join(',') + '\n'
      } else if (typeof row === 'object') {
        const values = headers.length > 0 
          ? headers.map(header => row[header] || '')
          : Object.values(row)
        csvContent += values.join(',') + '\n'
      }
    })
    
    return await copyText(csvContent, showMessage)
  } catch (error) {
    console.error('CSV格式化失败:', error)
    
    if (showMessage) {
      showToast({
        message: '复制失败：数据格式错误',
        type: 'fail',
        duration: 1500
      })
    }
    
    return false
  }
}

/**
 * 复制图片到剪贴板
 * @param {string} imageUrl - 图片URL
 * @param {boolean} showMessage - 是否显示提示消息
 * @returns {Promise<boolean>} 复制是否成功
 */
export const copyImage = async (imageUrl, showMessage = true) => {
  try {
    if (!navigator.clipboard || !navigator.clipboard.write) {
      throw new Error('浏览器不支持复制图片')
    }
    
    const response = await fetch(imageUrl)
    const blob = await response.blob()
    
    await navigator.clipboard.write([
      new ClipboardItem({
        [blob.type]: blob
      })
    ])
    
    if (showMessage) {
      showToast({
        message: '图片复制成功',
        type: 'success',
        duration: 1500
      })
    }
    
    return true
  } catch (error) {
    console.error('复制图片失败:', error)
    
    if (showMessage) {
      showToast({
        message: '复制图片失败',
        type: 'fail',
        duration: 1500
      })
    }
    
    return false
  }
}

export default {
  useClipboard,
  copyText,
  copyObject,
  copyUrl,
  copyCurrentUrl,
  copyTableAsCSV,
  copyImage
}